﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace SharepointUpload
{
    public partial class MainPage : UserControl
    {
        List<FileInfo> filesToUpload;
        OpenFileDialog fileDlg = new OpenFileDialog();
        List<UIElement> uiCollection = new List<UIElement>();
        ObservableCollection<object> fieldData = new ObservableCollection<object>();

        //2010 variables
        Site site;
        Web currWeb;
        ListCollection webLists;
        ContentTypeCollection contentTypes;
        FieldCollection fields;
        WebCollection allWebs;
        List<HeirarchyInfo> siteMapData = new List<HeirarchyInfo>();
        ClientContext context;
        List selectedList;
        List<Field> applicableFields = new List<Field>();
        List<List> validLists = new List<List>();
        Folder selectedFolder;
        FolderCollection availableFolders;

        public MainPage()
        {
            InitializeComponent();
            GridLength rowHeight = new GridLength(0.0);
            actionRow.Height = rowHeight;
            //add nodes for Lists and Webs
            TreeViewItem webNode = new TreeViewItem();
            TreeViewItem listNode = new TreeViewItem();
            //switching these two lines makes it so it will show whichever site you're running from
            context = ClientContext.Current;
            //context = new ClientContext("http://sanfcsp2010dev/");
            //get all web sites within site collection here
            site = context.Site;
            context.Load(site);
            //site.RootWeb.GetSubwebsForCurrentUser
            //allWebs = site.
            currWeb = context.Web;
            context.Load(currWeb);
            webLists = currWeb.Lists;
            context.Load(webLists);
            context.ExecuteQueryAsync(getWebInfoSucceeded, getWebInfoFailed);
        }

        #region context event handlers
        //populate treeview with current websites info
        public void getWebInfoSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(FillTreeView);
        }

        public void getWebInfoFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string message = e.Message;
        }

        public void getListInfoFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string message = e.Message;
        }

        public void getListInfoSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(FillContentTypes);
        }

        public void getContentFieldsSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(FillFields);
        }

        public void getContentFieldsFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }

        public string ListIcon(string listType)
        {
            return "";
        }

        public void AddedListItemSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(AddedListItemSucceedMessage);
        }

        public void AddedListItemFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }

        private void AddedListItemSucceedMessage()
        {
            statusLbl.Content = "Successfully added new item to list " + selectedList.Title;
            statusLbl.Visibility = System.Windows.Visibility.Visible;
        }

        private void UploadFileSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            uploadedFilesComplete++;
            Dispatcher.BeginInvoke(AddedFileSucceedMessage);
        }

        private void GetFoldersSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(showFolders);
        }

        private void GetFoldersFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }

        private void AddedFileSucceedMessage()
        {
            statusLbl.Content = "Completed Adding File " + uploadedFilesComplete.ToString() + " of " + fileDlg.Files.Count().ToString();
            statusLbl.Visibility = System.Windows.Visibility.Visible;
        }

        private void UploadFileFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }

        private void GetFolderSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(AddedListItemSucceedMessage);
        }

        private void GetFolderFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }

        private void GetFileSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            uploadedFilesComplete++;
        }

        private void GetFileFailed(object sender, ClientRequestFailedEventArgs e)
        {
            string msg = e.Message;
        }
        #endregion

        #region Fill data after results have been pulled
        private void FillFields() 
        {
            if (contentFields.Children.Count >= 1)
            {
                contentFields.Children.Clear();
            }
            GridLength rowHeight = new GridLength(24.0);
            contentFields.RowDefinitions.Clear();
            string libraryType = "List";
            if (selectedList.BaseType == BaseType.DocumentLibrary)
            {
                libraryType = "DocLib";
                addItemBtn.Visibility = System.Windows.Visibility.Collapsed;
                uploadBtn.Visibility = System.Windows.Visibility.Visible;
                selectFilesBtn.Visibility = System.Windows.Visibility.Visible;
                actionRow.Height = rowHeight;
                selectedFolder = selectedList.RootFolder;
                context.Load(selectedFolder);
                context.ExecuteQueryAsync(GetFolderSuccess, GetFolderFailed);
            }
            else
            {
                addItemBtn.Visibility = System.Windows.Visibility.Visible;
                selectFilesBtn.Visibility = System.Windows.Visibility.Collapsed;
                uploadBtn.Visibility = System.Windows.Visibility.Collapsed;
                actionRow.Height = rowHeight;
            }
            
            bool ignoreField = false;
            foreach (Field fld in fields)
            {
                ignoreField = false;
                //check for whether to ignore a field
                if (fld.Hidden == true | fld.ReadOnlyField == true)
                {
                    //ignore hidden fields
                    //for some reason this is returning as true when it's not
                    ignoreField = true;
                }
                //ignore non-user editable fields and default visible fields
                if (fld.Title == "Modified" |
                    fld.Title == "Document Modified By" |
                    fld.Title == "Created" |
                    fld.Title == "Document Created By" |
                    fld.Title == "Email internal" |
                    fld.Title == "Email External" |
                    fld.Title == "Create Email Link" |
                    fld.Title == "Request Feedback" |
                    fld.Title == "Intralinks Status" |
                    fld.Title == "Send to Intralinks?" |
                    fld.Title == "Content Type") 
                {
                    //if we are submitting files to this library we need to hide title/name as that's set by the filename
                    ignoreField = true;
                }
                if (libraryType == "List")
                {
                    if (fld.Title == "Name")
                    {
                        ignoreField = true;
                    }
                }
                if (libraryType == "DocLib")
                {
                    //item name is pulled from the document itself
                    if (fld.Title == "Title" | fld.Title == "Name")
                    {
                        ignoreField = true;
                    }
                }
                if (ignoreField == false)
                {
                    ParseFieldForDisplay(fld);
                }
            }
            /*double height = 0.0;
            foreach (RowDefinition row in contentFields.RowDefinitions)
            {
                height = height + row.Height.Value;
            }
            contentFields.Height = height;*/
            FadeIn.Begin();
        }

        private void FillTreeView()
        {
            foreach (List list in webLists)
            {
                if (list.Hidden == false)
                {
                    validLists.Add(list);
                }
            }
            siteMap.ItemsSource = validLists;
        }

        private void FillContentTypes()
        {
            if (contentTypes.Count > 1)
            {
                selectContentType.ItemsSource = contentTypes;
                //if the count of items is less than 3 just ignore the folder and display the right info
                if (contentTypes.Count < 3)
                {
                    foreach (ContentType type in contentTypes)
                    {
                        if (type.Name != "Folder")
                        {
                            fields = type.Fields;
                            context.Load(fields);
                            context.ExecuteQueryAsync(getContentFieldsSucceeded, getContentFieldsFailed);
                        }
                    }
                }
            }
            else
            {
                fields = contentTypes[0].Fields;
                context.Load(fields);
                context.ExecuteQueryAsync(getContentFieldsSucceeded, getContentFieldsFailed);
            }
        }

        public void ParseFieldForDisplay(Field field)
        {
            SolidColorBrush brush = new SolidColorBrush(Colors.Black);
            RowDefinition newRow = new RowDefinition();
            newRow.Height = new GridLength(30);
            int rowCounter = contentFields.RowDefinitions.Count;
            Label fieldLbl = new Label();
            fieldLbl.Foreground = brush;
            fieldLbl.FontWeight = FontWeights.Bold;
            fieldLbl.Margin = new Thickness(5);
            ColumnDefinition columnInfo = contentFields.ColumnDefinitions[1];
            double targetWidth = columnInfo.Width.Value;
            switch (field.FieldTypeKind.ToString())
            {
                case "Lookup":
                    FieldLookup lookup = (FieldLookup)field;
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    ComboBox fieldLookup = new ComboBox();
                    fieldLookup.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    Grid.SetRow(fieldLookup, rowCounter);
                    Grid.SetColumn(fieldLookup, 1);
                    fieldLookup.MinWidth = 200;
                    fieldLookup.Foreground = brush;
                    fieldLookup.Name = field.Title;
                    fieldLookup.Width = targetWidth;
                    ///TODO: Add lookup values as children of field
                    //uiCollection.Add(fieldLookup);
                    //contentFields.Children.Add(fieldLookup);
                    break;
                case "Microsoft.SharePoint.SPFieldBoolean":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    CheckBox checkBox = new CheckBox();
                    checkBox.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    checkBox.Foreground = brush;
                    checkBox.Width = 24;
                    Grid.SetRow(checkBox, rowCounter);
                    Grid.SetColumn(checkBox, 1);
                    checkBox.Name = field.Title;
                    uiCollection.Add(checkBox);
                    contentFields.Children.Add(checkBox);
                    break;
                case "MultiChoice":
                    FieldMultiChoice choice = (FieldMultiChoice)field;
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    //combobox choice
                    ComboBox fieldChoice = new ComboBox();
                    fieldChoice.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    fieldChoice.MinWidth = 200;
                    fieldChoice.Foreground = brush;
                    Grid.SetRow(fieldChoice, rowCounter);
                    Grid.SetColumn(fieldChoice, 1);
                    fieldChoice.Name = field.Title;
                    fieldChoice.Margin = new Thickness(5);
                    fieldChoice.Width = targetWidth;
                    //populate value's within the choice drop down
                    foreach(string option in choice.Choices)
                    {
                        fieldChoice.Items.Add(option);
                    }
                    uiCollection.Add(fieldChoice);
                    //custom text field for free form input
                    TextBox customChoice = new TextBox();
                    customChoice.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    customChoice.MinWidth = 175;
                    customChoice.Foreground = brush;
                    Grid.SetRow(customChoice, rowCounter);
                    Grid.SetColumn(customChoice, 1);
                    customChoice.Name = field.Title + "CUSTOM";
                    //add fields to content fields
                    contentFields.Children.Add(fieldChoice);
                    contentFields.Children.Add(customChoice);
                    break;
                case "Microsoft.SharePoint.SPFieldCurrency":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox fieldText = new TextBox();
                    fieldText.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    fieldText.MinWidth = 200;
                    fieldText.Foreground = brush;
                    Grid.SetRow(fieldText, rowCounter);
                    Grid.SetColumn(fieldText, 1);
                    fieldText.Name = field.Title;
                    fieldText.Text = "$0.00";
                    uiCollection.Add(fieldText);
                    contentFields.Children.Add(fieldText);
                    break;
                case "DateTime":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    DatePicker fieldDate = new DatePicker();
                    fieldDate.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    fieldDate.MinWidth = 200;
                    fieldDate.Foreground = brush;
                    Grid.SetRow(fieldDate, rowCounter);
                    Grid.SetColumn(fieldDate, 1);
                    fieldDate.Name = field.Title;
                    uiCollection.Add(fieldDate);
                    contentFields.Children.Add(fieldDate);
                    break;
                case "Microsoft.SharePoint.SPFieldMultiChoice":
                    break;
                case "Microsoft.SharePoint.SPFieldMultiColumn":
                    break;
                case "MultiLineText":
                    newRow.Height = new GridLength(40);
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox fieldTextBox = new TextBox();
                    fieldTextBox.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    fieldTextBox.MinWidth = 200;
                    fieldTextBox.Foreground = brush;
                    Grid.SetRow(fieldTextBox, rowCounter);
                    Grid.SetColumn(fieldTextBox, 1);
                    fieldTextBox.TextWrapping = TextWrapping.Wrap;
                    fieldTextBox.MaxHeight = 80;
                    fieldTextBox.MinHeight = 40;
                    fieldTextBox.Name = field.Title;
                    fieldTextBox.Width = targetWidth;
                    uiCollection.Add(fieldTextBox);
                    contentFields.Children.Add(fieldTextBox);
                    break;
                case "Note":
                    newRow.Height = new GridLength(40);
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox noteTextBox = new TextBox();
                    noteTextBox.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    noteTextBox.MinWidth = 200;
                    noteTextBox.Foreground = brush;
                    Grid.SetRow(noteTextBox, rowCounter);
                    Grid.SetColumn(noteTextBox, 1);
                    noteTextBox.TextWrapping = TextWrapping.Wrap;
                    noteTextBox.MaxHeight = 80;
                    noteTextBox.MinHeight = 40;
                    noteTextBox.Name = field.Title;
                    noteTextBox.Width = targetWidth;
                    uiCollection.Add(noteTextBox);
                    contentFields.Children.Add(noteTextBox);
                    break;
                case "Number":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox fieldNumber = new TextBox();
                    fieldNumber.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    fieldNumber.Foreground = brush;
                    fieldNumber.MinWidth = 200;
                    Grid.SetRow(fieldNumber, rowCounter);
                    Grid.SetColumn(fieldNumber, 1);
                    fieldNumber.Name = field.Title;
                    fieldNumber.Text = "Enter Number...";
                    uiCollection.Add(fieldNumber);
                    contentFields.Children.Add(fieldNumber);
                    break;
                case "Microsoft.SharePoint.SPFieldRatingScale":
                    break;
                case "Url":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox fieldUrl = new TextBox();
                    fieldUrl.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    fieldUrl.MinWidth = 200;
                    fieldUrl.Foreground = brush;
                    Grid.SetRow(fieldUrl, rowCounter);
                    Grid.SetColumn(fieldUrl, 1);
                    fieldUrl.Name = field.Title;
                    fieldUrl.Text = "Enter Web Address...";
                    fieldUrl.Width = targetWidth;
                    uiCollection.Add(fieldUrl);
                    contentFields.Children.Add(fieldUrl);
                    break;
                case "Text":
                    contentFields.RowDefinitions.Add(newRow);
                    fieldLbl.Content = field.Title;
                    Grid.SetRow(fieldLbl, rowCounter);
                    Grid.SetColumn(fieldLbl, 0);
                    contentFields.Children.Add(fieldLbl);
                    TextBox fieldSingleLineText = new TextBox();
                    fieldSingleLineText.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    fieldSingleLineText.MinWidth = 200;
                    fieldSingleLineText.Foreground = brush;
                    Grid.SetRow(fieldSingleLineText, rowCounter);
                    Grid.SetColumn(fieldSingleLineText, 1);
                    fieldSingleLineText.Margin = new Thickness(5);
                    fieldSingleLineText.MaxLength = 200;
                    fieldSingleLineText.Name = field.Title;
                    fieldSingleLineText.Width = targetWidth;
                    uiCollection.Add(fieldSingleLineText);
                    contentFields.Children.Add(fieldSingleLineText);
                    break;
                case "Microsoft.SharePoint.SPFieldUser":
                    break;
            }
        }

        //show heirarchy of folders under current library
        private void showFolders()
        {
            //TreeViewItem selectedNode = (TreeViewItem)siteMap.SelectedItem;
            //selectedNode.ItemsSource = availableFolders;
        }
            #endregion

        #region form event handlers
        public ContentType selectedContentType;

        private void selectContentType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                selectedContentType = (ContentType)e.AddedItems[0];
                fields = selectedContentType.Fields;
                context.Load(fields);
                context.ExecuteQueryAsync(getContentFieldsSucceeded, getContentFieldsFailed);
            }
            catch (IndexOutOfRangeException ex)
            {
                //happens when switching lists
            }
        }

        void FadeOut_Completed(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        void FadeIn_Completed(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            fileDlg.Multiselect = true;
            fileDlg.ShowDialog();
        }

        private void siteMap_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            //first treat the node as a library
            selectedList = (List)e.NewValue;
            //pull content types from list
            context.Load(selectedList);
            contentTypes = selectedList.ContentTypes;
            context.Load(contentTypes);
            context.ExecuteQueryAsync(getListInfoSucceeded, getListInfoFailed);
            availableFolders = selectedList.RootFolder.Folders;
            context.Load(availableFolders);
            context.ExecuteQueryAsync(GetFoldersSuccess, GetFoldersFailed);
            /*try
            {
                
            }
            catch (Exception)
            {
                //if that fails treat the node as a folder
                selectedFolder = (Folder)e.NewValue;
                context.Load(selectedFolder);
                context.ExecuteQueryAsync(GetFolderSuccess, GetFolderFailed);
            }*/
        }

        public void Button_Click_1(object sender, RoutedEventArgs e)
        {
            UploadFiles();
        }

        private void addItemBtn_Click(object sender, RoutedEventArgs e)
        {
            newListItem = selectedList.AddItem(new ListItemCreationInformation());
            BuildListItem(newListItem);
        }
        #endregion

        #region Upload Files and Add Metadata Async
        public void UploadFiles()
        {
            //get current field values
            if (fileDlg.File == null)
            {
                statusLbl.Content = "Error: No files selected.";
                statusLbl.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                FileCreationInformation newFile;
                Microsoft.SharePoint.Client.File fileToUpload;
                int i = 1;
                FileToUploadCount = fileDlg.Files.Count();
                foreach (FileInfo file in fileDlg.Files)
                {
                    newFile = new FileCreationInformation();
                    newFile.Overwrite = true;
                    statusLbl.Content = "Uploading File " + i.ToString() + " of " + fileDlg.Files.Count().ToString();
                    Stream fStream = file.OpenRead();
                    BinaryReader br = new BinaryReader(fStream);
                    long fileSize = file.Length;
                    byte[] fileData = br.ReadBytes((int)fileSize);
                    newFile.Content = fileData;
                    //if no folder is selected put in root of library
                    if (selectedFolder == null)
                    {
                        newFile.Url = context.Site.Url + "" + selectedFolder.ServerRelativeUrl + "/" + file.Name;
                        fileToUpload = selectedList.RootFolder.Files.Add(newFile);
                    }
                        //otherwise upload to the selected folder, makes sense huh?
                    else
                    {
                        newFile.Url = context.Site.Url + "" + selectedFolder.ServerRelativeUrl + "/" + file.Name;
                        fileToUpload = selectedFolder.Files.Add(newFile);
                    }
                    context.Load(fileToUpload);
                    uploadedFiles.Add(fileToUpload);
                    context.ExecuteQueryAsync(UploadFileSuccess, UploadFileFailed);
                    br.Close();
                    i++;
                }
                ThreadStart ts = new ThreadStart(MonitorUploads);
                Thread t = new Thread(ts);
                t.Start();
            }
        }

        int uploadedFilesComplete = 0;
        int FileToUploadCount;

        public List<Microsoft.SharePoint.Client.File> uploadedFiles = new List<Microsoft.SharePoint.Client.File>();
        public List<ListItem> uploadFileItems = new List<ListItem>();

        //wait for uploads to complete
        public void MonitorUploads()
        {
            if (uploadedFilesComplete == FileToUploadCount)
            {
                uploadedFilesComplete = 0;
                Dispatcher.BeginInvoke(UpdateListItems);
            }
            else
            {
                //wait and then recheck
                //may want to decrease from 5 to 1 seconds
                System.Threading.Thread.Sleep(5000);
                MonitorUploads();
            }
        }

        //add metadata to newly uploaded documents
        public void UpdateListItems()
        {
            foreach(Microsoft.SharePoint.Client.File uploadedFile in uploadedFiles) 
            {
                foreach (Field field in fields)
                {
                    string fldInfo = field.TypeDisplayName;
                    var currentField = contentFields.FindName(field.Title);
                    if (currentField != null)
                    {
                        switch (currentField.ToString())
                        {
                            case ("System.Windows.Controls.TextBox"):
                                TextBox textField = currentField as TextBox;
                                if (textField.Text != "")
                                {
                                    uploadedFile.ListItemAllFields[field.StaticName] = textField.Text;
                                }
                                break;
                            case ("System.Windows.Controls.DatePicker"):
                                DatePicker dateField = currentField as DatePicker;
                                if (dateField.SelectedDate.ToString() != "")
                                {
                                    uploadedFile.ListItemAllFields[field.StaticName] = dateField.SelectedDate.ToString();
                                }
                                break;
                            case ("System.Windows.Controls.ComboBox"):
                                ComboBox dropDownField = currentField as ComboBox;

                                if (dropDownField.SelectedItem != null)
                                {
                                    uploadedFile.ListItemAllFields[field.StaticName] = dropDownField.SelectedItem.ToString();
                                }
                                break;
                            case ("System.Windows.Controls.CheckBox"):
                                CheckBox booleanField = currentField as CheckBox;
                                //TODO: Need to fix this so the checkbox's have there own event handler for checked/unchecked otherwise 
                                //if someone doesn't set a value it's automatically false
                                if (booleanField.IsChecked == true)
                                {
                                    uploadedFile.ListItemAllFields[field.StaticName] = true;
                                }
                                if (booleanField.IsChecked == false)
                                {
                                    uploadedFile.ListItemAllFields[field.StaticName] = false;
                                }
                                break;
                        }
                    }
                }
                uploadedFile.ListItemAllFields.Update();
                context.Load(uploadedFile);
                context.ExecuteQueryAsync(AddedListItemSuccess, AddedListItemFailed);
            }
            fileDlg = new OpenFileDialog();
        }
        #endregion

        #region Create New ListItem

        public ListItem newListItem;

        internal void BuildListItem(ListItem newUpdatedItem)
        {
            foreach (Field field in fields)
            {
                string fldInfo = field.TypeDisplayName;
                var currentField = contentFields.FindName(field.Title);
                if (currentField != null)
                {
                    switch (currentField.ToString())
                    {
                        case ("System.Windows.Controls.TextBox"):
                            TextBox textField = currentField as TextBox;
                            if (textField.Text != "")
                            {
                                newUpdatedItem[field.StaticName] = textField.Text;
                            }
                            break;
                        case ("System.Windows.Controls.DatePicker"):
                            DatePicker dateField = currentField as DatePicker;
                            if (dateField.SelectedDate.ToString() != "")
                            {
                                newUpdatedItem[field.StaticName] = dateField.SelectedDate.ToString();
                            }
                            break;
                        case ("System.Windows.Controls.ComboBox"):
                            ComboBox dropDownField = currentField as ComboBox;
                                
                            if (dropDownField.SelectedItem != null)
                            {
                                newUpdatedItem[field.StaticName] = dropDownField.SelectedItem.ToString();
                            }
                            break;
                        case ("System.Windows.Controls.CheckBox"):
                            CheckBox booleanField = currentField as CheckBox;
                            //TODO: Need to fix this so the checkbox's have there own event handler for checked/unchecked otherwise 
                            //if someone doesn't set a value it's automatically false
                            if (booleanField.IsChecked == true)
                            {
                                newUpdatedItem[field.StaticName] = true;
                            }
                            if (booleanField.IsChecked == false)
                            {
                                newUpdatedItem[field.StaticName] = false;
                            }
                            break;
                    }
                }
            }
            newListItem = newUpdatedItem;
            context.Load(newListItem);
            context.ExecuteQueryAsync(AddedListItemSuccess, AddedListItemFailed);
        }
        #endregion
    }

    public class HeirarchyInfo
    {
        public int id { get; set; }
        public string name { get; set; }
        public string url { get; set; }
        public string imageUrl { get; set; }
        public string web { get; set; }
        public string type { get; set; }
        public List<HeirarchyInfo> children { get; set; }
    }
}
